<?php

/** 
 * 后台_买水_控制器
 * @property School_mdl $school
 * @property Dev_mdl $dev
 * @property User_mdl $user
 * @property User_order_mdl $userOrder
 * @property Order_cache_mdl $orderCache
 * @property CI_Cache $cache
 */
class Buy extends Admin_Controller {
	public function __construct() {
		parent::__construct ();
		$this->load->model ( 'School_mdl', 'school' );
		$this->load->driver ( 'cache', array (
				'adapter' => 'file',
				'backup' => 'file' 
		) );
	}
	protected function search($query) {
		$where = array ();
		$order = 'updateTime';
		$sort = 'DESC';
		$page = 1;
		$pagesize = 20;
		extract ( $query );
		
		$limit = $pagesize > 0 ? $pagesize : 20;
		$offset = ($page - 1) * $limit;
		if ($offset) {
			$limitSql = "{$offset},{$limit}";
		} else {
			$limitSql = "{$limit}";
		}
		
		$unionTables = array ();
		$tidSet = array (
				0,
				1,
				2,
				3,
				4,
				5,
				6,
				7,
				8,
				9 
		);
		
		$whereSql = '';
		if (! empty ( $where )) {
			$whereSql = ' WHERE ';
			$whereSql .= implode ( ' AND ', $where );
		}
		$_limit = ($offset + $limit) * 10;
		foreach ( $tidSet as $tid ) {
			$table = 'hs_order_' . $tid;
			$sql = "SELECT * FROM (
			SELECT * FROM `{$table}`
			{$whereSql}
			ORDER BY `{$order}` {$sort}
			LIMIT {$_limit}
			) AS t{$tid}";
			$unionTables [] = $sql;
		}
		
		$unionTable = implode ( ' UNION ', $unionTables );
		
		$sql = "SELECT * FROM ({$unionTable}) as t ORDER BY t.`updateTime` DESC LIMIT {$limitSql}";
		
		// echo $sql;die;
		$list = $this->db->query ( $sql )->result_array ();
		// if( empty($whereSql) ){
		// $totalRowsSQL = "select sum(NUM_ROWS) as total from information_schema.`INNODB_SYS_TABLESTATS` where NAME REGEXP 'heshui/hs_order_[0-9]'";
		// $totalRows = $this->db->query($totalRowsSQL)->row()->total;
		// }else{
		$unionTables = array ();
		foreach ( $tidSet as $tid ) {
			$table = 'hs_order_' . $tid;
			$sql = "SELECT count(*) as _total FROM {$table} {$whereSql}";
			$unionTables [] = $sql;
		}
		$unionTables = implode ( ' UNION ', $unionTables );
		$sql = "SELECT sum(_total) as total FROM ($unionTables) as t";
		$cacheKey = md5 ( $sql );
		$totalRows = $this->cache->get ( $cacheKey );
		if (empty ( $totalRows )) {
			$totalRows = $this->db->query ( $sql )->row ()->total;
			$this->cache->save ( $cacheKey, $totalRows, 60 );
		}
		
		// }
		
		$this->searchTpl->setPagins ( $page, $totalRows, $limit );
		return $list;
	}
	
	/**
	 * 买水订单视图
	 */
	public function order() {
		$this->load->library ( 'Search_tpl', NULL, 'searchTpl' );
		// error_reporting(-1);
		// ini_set('display_errors', 1);
		// $this->searchTpl->debug = TRUE;
		// $table = 'hs_order_all_view';
		$table = NULL;
		$where = array ();
		$like = array ();
		$order = 'updateTime';
		$sort = 'DESC';
		$orders = array (
				'orderID' => 'id',
				'uid' => 'userID',
				'time' => 'time',
				'amount' => 'amount',
				'time' => 'updateTime' 
		);
		$page = 1;
		$pagesize = 20;
		$input = $this->input->get ( NULL, TRUE );
		foreach ( $input as $k => $v ) {
			if ($v === '') {
				continue;
			}
			$v = trim ( $v );
			switch ($k) {
				case 'orderID' :
					$v = ( int ) $v;
					if ($v <= 0)
						continue;
					$tableID = floor ( $v / 1e8 );
					if ($tableID >= 10)
						continue;
					$where [] = 'id = ' . ($v % 1e8);
					$table = 'hs_order_' . $tableID;
					break;
				case 'uid' :
					$where [] = 'userID = ' . ( int ) $v;
					$table = 'hs_order_' . ($v % 10);
					break;
				// case 'nickname':
				// $_users = $this->db->select('id')->like('nickname',$v)->get(MY_Model::T_USER)->result_array();
				// $where_in[] = array('field'=>'userID','list'=>array_column($_users, 'id'));
				// $like['nickname'] = $v;
				// break;
				case 'tradeState' :
					if ($v != 'ALL') {
						$where ['tradeState'] = $v;
					}
					break;
				case 'st' :
					$where [] = 'updateTime >= ' . ( float ) strtotime ( $v );
					// $where['createTime >= '] = (float)strtotime($v);
					break;
				case 'et' :
					$where [] = 'updateTime <= ' . ( float ) strtotime ( $v );
					break;
				case 'order' :
					$order = isset ( $orders [$v] ) ? $orders [$v] : 'updateTime';
					break;
				case 'sort' :
					$sort = ( int ) $v === 0 ? 'DESC' : 'ASC';
					break;
				// case 'schoolID':
				// $v = (int)$v;
				// if( $v ){
				// $where['schoolID'] = $v;
				// }
				case 'page' :
					$v = ( int ) $v;
					if ($v > 0) {
						$page = $v;
					}
					break;
				case 'pagesize' :
					$v = ( int ) $v;
					if ($v > 0) {
						$pagesize = $v;
					}
					break;
			}
		}
		$user=$_SESSION['admin'];
		if( empty($user) ){
			alert('未登录！',ADMIN_DIR.'login/login');
		}
		$school_id=isset($user['school_id'])?$user['school_id']:0;
		$where_array=array();
		if($school_id>0){
			$where['schoolID']=(int)$school_id;
			$where_array['id']=$school_id;
		}
		
		$query = array ();
		$query ['select'] = '*';
		$query ['where'] = $where;
		$query ['like'] = $like;
		$query ['order'] = $order;
		$query ['sort'] = $sort;
		
		if (empty ( $table )) {
			$query ['page'] = $page;
			$query ['pagesize'] = $pagesize;
			$list = $this->search ( $query );
		} else {
			$query ['from'] = $table;
			$list = $this->searchTpl->query ( $query );
		}
		$this->load->model ( 'admin_mdl', 'adminmdl' );
		$is_admin=$this->adminmdl->isSuperManager($user['id']);
		 
		if($is_admin){
			$schools = $this->school->getSchoolList();
		}else{
			$schools = $this->school->getSchoolList ($where_array);
		}
		
	
		if (! empty ( $list )) {
			$list = $this->getTableRows ( $list,$school_id );
		}
		
		// $this->load->model('Dev_mdl','dev');
		// $this->load->model('User_mdl','users');
		
		$temp = array ();
		$temp ['formItems'] = array (
				'orderID',
				'uid',
				// 'nickname',
				// 'school',
				'br',
				'st',
				'et' 
		);
		$temp ['thList'] = $this->getTableThItems ();
		$temp ['tdList'] = $list;
		$temp ['tableTitle'] = '订单列表--共查到%s张订单--';
		$temp ['jsCtrl'] = 'buyOrderCtrl';
		$temp ['header'] = $this->getViewHeaderData ();
		$temp ['schoolList'] = $schools;
		$this->searchTpl->show ( $temp );
	}
	public function stat() {
		$type = $this->input->post_get ( 'type', TRUE );
		$user=$_SESSION['admin'];
		if( empty($user) ){
			alert('未登录！',ADMIN_DIR.'login/login');
		}
		 $school_id=0;
		if($user['id']!=14){
			$school_id=isset($user['school_id'])?$user['school_id']:0;

		}
		//$school_id=isset($user['school_id'])?$user['school_id']:0;
	// var_dump($school_id,$user);die;
		if($school_id!=0){
			$school_id_arr=explode(',',$school_id);
			 $school_id=intval($school_id_arr[0]); 
		}
		if(isset($_REQUEST['schoolID'])&&$_REQUEST['schoolID']>0){
			$school_id=$_REQUEST['schoolID'];
		}
	
		switch ($type) {
			case 'chart' : // "统计图表"数据
				$this->load->model ( 'Order_cache_mdl', 'orderCache' );
				$this->chartData ($school_id);
				break;
			case 'list' : // "详细记录"数据
				$this->load->model ( 'Order_cache_mdl', 'orderCache' );
				$this->listData ($school_id);
				break;
			default : // 输出html
			 
				$this->statHTML ();
				break;
		}
	}
	public function dev_stat() { 
		
		$user=$_SESSION['admin'];
		
		if( empty($user) ){
			alert('未登录！',ADMIN_DIR.'login/login');
		}
		
		$school_id=isset($user['school_id'])?$user['school_id']:0; 
		
		if($school_id!=0){
			$school_id_arr=explode(',',$school_id);
			foreach($school_id_arr as $val){
				if($val>0){
					$school_id=intval($school_id_arr[0]);break;
				}
			} 	
		}else{
			alert('无此学校权限','back');
		}
		$this->load->model ( 'admin_mdl', 'adminmdl' );
		$is_admin=$this->adminmdl->isSuperManager($user['id']);
		if($is_admin){
			$school_list = $this->school->getSchoolList();
		}else{
			$school_list = $this->school->getSchoolList('',$school_id_arr);
		} 
		
		$this->load->model ( 'Tongji_mongo_mdl', 'tongji' );
		 
	  	$input = &$_REQUEST;

	  	$yesterday = date('Y-m-d',time()-24*3600);
	  	
		$query = array ('sid'=>$school_id,'ctime'=>array('$gte'=>$yesterday));
		$params = array('school'=>$school_id,'rc_st'=>$yesterday); 
		$ctime = array();
		
		foreach ( $input as $k => $v ) {
			$v = trim ( $v );
			if ($v === '') {
				continue;
			} 
			switch ($k) {
				case 'school' :
					$v = ( int ) $v;
					$school_id = $v;
					if ($v > 0) {
						$params['school']=$v;
						$query ['sid'] = $v;
					}
					break;  
				case 'rc_st' :
					$params['rc_st']=$v;
					$query ['ctime']['$gte'] = $v;
					break;
				case 'rc_et' :
					$params['rc_et']=$v;
					$query ['ctime']['$lte'] = $v;
					break;  
			}
		}
		
		$str = '';
		foreach ( $params as $p=>$pval){
			if (empty($str)){
				$str = '?'.$p.'='.$pval;
			}else{
				$str .= '&'.$p.'='.$pval;
			}
		}
	
		$sortKeys = array (
				'take_sec' => 'take_sec',
				'price_count' => 'price_count',
				'did' => 'did',
				'usercount' => 'usercount',
				't_1' => 't_1',
				't_2' => 't_2',
				't_3' => 't_3'
		);
		
		$pagedata = check_page();
		$page = ( int ) $this->input->post_get ( 'page' );
		$page = $page > 0 ? $page : 1;
		$pagesize = ( int ) $this->input->post_get ( 'pagesize' );
		$pagesize = $pagesize > 0 ? $pagesize : 20;
		
		$sortKey = $this->input->post_get ( 'order', TRUE );
		$sortKey = isset ( $sortKeys [$sortKey] ) ? $sortKeys [$sortKey] : 'price_count';
		$sortVal = ( int ) $this->input->post_get ( 'sort' );
		$sortVal = $sortVal > 0 ? 1 : - 1;
		
		$fields = array ();
		$limit = '';
		$offset = '';
		
		$sort = array (
				$sortKey => $sortVal
		);
		
		if($school_id>0){
			$query['sid']=$school_id;
		}
		 
		$list = $this->tongji->getDevTongji( $fields, $query, $sort ,$sortKey);
		$count = $this->tongji->count ( $query ); 
		
		$pagestring = pagestring($count, $pagedata);
		
		$temp['list'] = $list;
		$temp['page'] = $pagestring; 
		$temp['school'] = $school_list;
		$temp['schoolid'] = $school_id;
		$temp['rc_st'] = !empty($input['rc_st'])?$input['rc_st']:'';
		$temp['rc_et'] = !empty($input['rc_et'])?$input['rc_et']:'';
		$temp['params'] = $str;
		$this->showView('admin/buy/get_list',$temp);  
		
	} 
	
	public function user_stat() {
		
		$user=$_SESSION['admin'];
		if( empty($user) ){
			alert('未登录！',ADMIN_DIR.'login/login');
		}
		$school_id=isset($user['school_id'])?$user['school_id']:0;
		if($school_id!=0){
			$school_id_arr=explode(',',$school_id);
			foreach($school_id_arr as $val){
				if($val>0){
					$school_id=intval($school_id_arr[0]);break;
				}
			}
		}else{
			alert('无此学校权限','back');
		}
		$this->load->model ( 'admin_mdl', 'adminmdl' );
		$is_admin=$this->adminmdl->isSuperManager($user['id']);
		
		if($is_admin){
			$school_list = $this->school->getSchoolList();
		}else{
			$school_list = $this->school->getSchoolList('',$school_id_arr);
		} 
		
		$this->load->model ( 'Tongji_user_mdl', 'tongji' );
			
		$input = &$_REQUEST;
		$yesterday = date('Y-m-d',time()-24*3600);
	  	
		$query = array ('sid'=>$school_id,'ctime'=>array('$gte'=>$yesterday));
		$params = array('school'=>$school_id,'rc_st'=>$yesterday); 
		$ctime = array();
		
		foreach ( $input as $k => $v ) {
			$v = trim ( $v );
			if ($v === '') {
				continue;
			} 
			switch ($k) {
				case 'school' :
					$v = ( int ) $v;
					$school_id = $v;
					if ($v > 0) {
						$params['school']=$v;
						$query ['sid'] = $v;
					}
					break;  
				case 'rc_st' :
					$params['rc_st']=$v;
					$query ['ctime']['$gte'] = $v;
					break;
				case 'rc_et' :
					$params['rc_et']=$v;
					$query ['ctime']['$lte'] = $v;
					break;  
			}
		}
		
		$str = '';
		foreach ( $params as $p=>$pval){
			if (empty($str)){
				$str = '?'.$p.'='.$pval;
			}else{
				$str .= '&'.$p.'='.$pval;
			}
		}
		
		$sortKeys = array (
				'take_sec' => 'take_sec',
				'price_count' => 'price_count',
				'uid' => 'uid', 
				't_1' => 't_1',
				't_2' => 't_2',
				't_3' => 't_3'
		);
		
		$pagedata = check_page();
		$page = ( int ) $this->input->post_get ( 'page' );
		$page = $page > 0 ? $page : 1;
		$pagesize = ( int ) $this->input->post_get ( 'pagesize' );
		$pagesize = $pagesize > 0 ? $pagesize : 20;
		$sortKey = $this->input->post_get ( 'order', TRUE );
		$sortKey = isset ( $sortKeys [$sortKey] ) ? $sortKeys [$sortKey] : 'price_count';
		$sortVal = ( int ) $this->input->post_get ( 'sort' );
		$sortVal = $sortVal > 0 ? 1 : - 1;
	
		$fields = array ();
		$sort = array (
				$sortKey => $sortVal
		);
		if($school_id>0){
			$query['sid']=$school_id;
		}
		
		$list = $this->tongji->getUserTongji( $fields, $query, $sort,$sortKey );
		$count = $this->tongji->count ( $query );
		$pagestring = pagestring($count, $pagedata);
		
		$temp['list'] = $list;
		$temp['page'] = $pagestring;
		$temp['school'] = $school_list;
		$temp['schoolid'] = $school_id;
		$temp['rc_st'] = !empty($input['rc_st'])?$input['rc_st']:'';
		$temp['rc_et'] = !empty($input['rc_et'])?$input['rc_et']:'';
		$temp['params'] = $str;
		
		$this->showView('admin/buy/get_list_user',$temp);
	}
	
	public function user_recharge_stat() {
	
		$user=$_SESSION['admin'];
		
		if( empty($user) ){
			alert('未登录！',ADMIN_DIR.'login/login');
		}
		
		$school_id=isset($user['school_id'])?$user['school_id']:0;
		
		if($school_id!=0){
			$school_id_arr=explode(',',$school_id);
			foreach($school_id_arr as $val){
				if($val>0){
					$school_id=intval($school_id_arr[0]);break;
				}
			}
		}else{
			alert('无此学校权限','back');
		}
	
		$school_list = $this->school->getSchoolList('',$school_id_arr);
		$this->load->model ( 'Tongji_user_recharge_mdl', 'tongji' );
			
		$input = &$_REQUEST;
		$yesterday = date('Y-m-d',time()-24*3600);
	
		$query = array ('sid'=>$school_id,'ctime'=>array('$gte'=>$yesterday));
		$params = array('school'=>$school_id,'rc_st'=>$yesterday);
		$ctime = array();
	
		foreach ( $input as $k => $v ) {
			$v = trim ( $v );
			if ($v === '') {
				continue;
			}
			switch ($k) {
				case 'school' :
					$v = ( int ) $v;
					$school_id = $v;
					if ($v > 0) {
						$params['school']=$v;
						$query ['sid'] = $v;
					}
					break;
				case 'rc_st' :
					$params['rc_st']=$v;
					$query ['ctime']['$gte'] = $v;
					break;
				case 'rc_et' :
					$params['rc_et']=$v;
					$query ['ctime']['$lte'] = $v;
					break;
			}
		}
	
		$str = '';
		foreach ( $params as $p=>$pval){
			if (empty($str)){
				$str = '?'.$p.'='.$pval;
			}else{
				$str .= '&'.$p.'='.$pval;
			}
		}
	
		$sortKeys = array (
				'take_sec' => 'take_sec',
				'amount_count' => 'amount_count',
				'uid' => 'uid',
		);
	
		$pagedata = check_page();
		$page = ( int ) $this->input->post_get ( 'page' );
		$page = $page > 0 ? $page : 1;
		$pagesize = ( int ) $this->input->post_get ( 'pagesize' );
		$pagesize = $pagesize > 0 ? $pagesize : 20;
		$sortKey = $this->input->post_get ( 'order', TRUE );
		$sortKey = isset ( $sortKeys [$sortKey] ) ? $sortKeys [$sortKey] : 'amount_count';
		$sortVal = ( int ) $this->input->post_get ( 'sort' );
		$sortVal = $sortVal > 0 ? 1 : - 1;
	
		$fields = array ();
		$sort = array (
				$sortKey => $sortVal
		);
		if($school_id>0){
			$query['sid']=$school_id;
		}
	
		$list = $this->tongji->getUserTongji( $fields, $query, $sort,$sortKey );
		$count = $this->tongji->count ( $query );
		$pagestring = pagestring($count, $pagedata);
	
		$temp['list'] = $list;
		$temp['page'] = $pagestring;
		$temp['school'] = $school_list;
		$temp['schoolid'] = $school_id;
		$temp['rc_st'] = !empty($input['rc_st'])?$input['rc_st']:'';
		$temp['rc_et'] = !empty($input['rc_et'])?$input['rc_et']:'';
		$temp['params'] = $str;
	
		$this->showView('admin/buy/get_list_user_recharge',$temp);
	}
	
	/**
	 * 查看一个用户订单
	 */
	public function user_order() {
		// $this->load->library('Search_tpl',NULL,'searchTpl');
		$this->load->model ( 'User_mdl', 'user' );
		$this->load->model ( 'User_order_mdl', 'userOrder' );
		
		$uid = ( int ) $this->input->post_get ( 'uid' );
		$user = $this->user->getOneById ( $uid );
		if (empty ( $user )) {
			$this->apiOutput->error ( '查不到该用户信息' );
			exit ();
		}
		
		$list = $this->userOrder->getUserOrders ( $uid );
		array_walk ( $list, function (&$order) {
			$order ['id'] = sprintf ( "%1d%08d", $order ['userID'] % 10, $order ['id'] );
			$order ['createTime'] = date ( 'Y-m-d H:i:s', $order ['createTime'] );
		} );
		
		// $list = $this->getTableRows($list);
		$this->apiOutput->put ( 'list', $list )->out ();
		// $temp ['thList'] = $this->getTableThItems();
		// $temp['tdList'] = $list;
		// $temp['tableTitle'] = '订单列表--共查到%s张订单--';
		// $temp['jsCtrl'] = 'buyOrderCtrl';
		// $temp['header'] = $this->getViewHeaderData();
		// $this->searchTpl->show($temp);
	}
	public function close_order() {
		$uid = ( int ) $this->input->post_get ( 'uid' );
		$orderID = ( int ) $this->input->post_get ( 'orderID' );
		$orderID = $orderID % 1e8;
		$this->load->model ( 'User_order_mdl', 'userOrder' );
		$this->userOrder->setUserID ( $uid );
		$update = array (
				'isFinish' => 1 
		);
		$res = $this->userOrder->updateOne ( 'id', $orderID, $update );
		
		if ($res) {
			$this->apiOutput->out ();
		} else {
			$this->apiOutput->errorSystem ();
		}
	}
	private function statHTML() {
		$formItems = array (
				array (
						'type' => 'text',
						'name' => 'uid',
						'label' => '用户ID' 
				),
				array (
						'type' => 'text',
						'name' => 'nickname',
						'label' => '用户昵称' 
				),
				array (
						'type' => 'text',
						'name' => 'devID',
						'label' => '设备ID' 
				),
				array (
						'type' => 'text',
						'name' => 'devName',
						'label' => '设备名称' 
				),
				'school',
				'br',
				array (
						'type' => 'dateRange',
						'label' => '消费时间',
						'begin' => array (
								'name' => 'rc_st',
								'value' => date ( 'Y-m-d 00:00:00', time () - 86400 ) 
						),
						'end' => array (
								'name' => 'rc_et',
								'value' => date ( 'Y-m-d 23:59:59' ) 
						) 
				) 
		);
		$statTemp = array (
				'config' => array (
						'api' => base_url ( ADMIN_DIR . 'buy/stat' ),
						'thItems' => $this->getTableThItems (),
						'tdClass' => array (
								3 => 'amount',
								8 => 'userID',
								9 => 'username' 
						) 
				) 
		);
		$this->showHeader ();
		$this->showSearchForm ( $formItems );
		$this->showStat ( $statTemp );
		$this->showFooter ();
	}
	private function listData($schoolID=0) {
		$query = $this->getQuery ();
		$input = &$_REQUEST;
		$sortKeys = array (
				'orderID' => '_id',
				'uid' => 'userID',
				'devID' => 'devID',
				'time' => 'createTime' 
		);
		$page = ( int ) $this->input->post_get ( 'page' );
		$page = $page > 0 ? $page : 1;
		$pagesize = ( int ) $this->input->post_get ( 'pagesize' );
		$pagesize = $pagesize > 0 ? $pagesize : 20;
		$sortKey = $this->input->post_get ( 'order', TRUE );
		$sortKey = isset ( $sortKeys [$sortKey] ) ? $sortKeys [$sortKey] : 'createTime';
		$sortVal = ( int ) $this->input->post_get ( 'sort' );
		$sortVal = $sortVal > 0 ? 1 : - 1;
		
		$fields = array ();
		$limit = $pagesize;
		$offset = ($page - 1) * $pagesize;
		$sort = array (
				$sortKey => $sortVal 
		);
		if($schoolID>0){
			$query['schoolID']=(int)$schoolID;
		}
		
		$list = $this->orderCache->getOrders ( $fields, $query, $limit, $offset, $sort );
		if (! empty ( $list )) {
			$list = $this->getTableRows ( $list,$schoolID );
		}
		
		if ($page === 1) {
			$total = $this->orderCache->count ( $query );
			$this->apiOutput->put ( 'total', $total );
		}
		
		$this->apiOutput->put ( 'list', $list )->out ();
	}
	 
	/**
	 * 图表处理
	 */
	private function chartData($schoolID=0) {
		$query = $this->getQuery ();
		if (empty ( $query ['createTime'] ['$gte'] )) {
			$query ['createTime'] ['$gte'] = time () - 86400;
		}
		if (empty ( $query ['createTime'] ['$lte'] )) {
			$query ['createTime'] ['$lte'] = time ();
		}
		
		$beginTime = $query ['createTime'] ['$gte'];
		$endTime = $query ['createTime'] ['$lte'];
		if($schoolID>0){
			$query['schoolID']=(int)$schoolID;
		}
		//var_dump($query);die;
		$list = $this->orderCache->statByDaily ( $query );
		// 横坐标数组(日期)
		$dateList = array ();
		// 消费金额数组
		$amountList = array ();
		// 消费次数数组
		$timesList = array ();
		// 总消费金额
		$totalAmount = 0;
		// 总消费次数
		$totalTimes = 0;
		if (! empty ( $list )) {
			foreach ( $list as $v ) {
				$totalAmount += $v ['totalAmount'];
				$totalTimes += $v ['times'];
				
				if (empty ( $v ['_id'] ))
					continue;
					// _id : 160101;
				$date = "20" . (implode ( '-', sscanf ( $v ['_id'], "%2d%2d%2d" ) ));
				$dateList [] = $date;
				$amountList [] = $v ['totalAmount'] / 100;
				$timesList [] = $v ['times'];
			}
		}
		
		// 图表配置数组
		$chart = array (
				'xAxis' => array ( // 横坐标
						'data' => $dateList,
						'type' => 'category',
						'name' => '日期',
						'boundaryGap' => false 
				),
				'yAxis' => array (
						array (
								'name' => '金额/元',
								'type' => 'value' 
						),
						array (
								'name' => '次数/次',
								'type' => 'value' 
						) 
				),
				'legend' => array (
						'data' => array (
								'消费金额',
								'消费次数' 
						) 
				),
				'series' => array (
						array (
								'name' => '消费金额',
								'type' => 'line',
								'data' => $amountList 
						),
						array (
								'name' => '消费次数',
								'yAxisIndex' => 1,
								'type' => 'line',
								'data' => $timesList 
						) 
				),
				'tooltip' => array (
						'trigger' => 'axis' 
				) 
		);
		
		$stat = array (
				array (
						'th' => '消费时间',
						'td' => date ( 'Y-m-d H:i:s', $beginTime ) . '至' . date ( 'Y-m-d H:i:s', $endTime ) 
				),
				array (
						'th' => '总消费金额',
						'td' => ($totalAmount / 100) . '元' 
				),
				array (
						'th' => '总消费次数',
						'td' => ($totalTimes) . '次' 
				) 
		);
		$this->apiOutput->put ( 'chart', $chart )->put ( 'stat', $stat )->out ();
	}
	private function getQuery($input = array()) {
		if (empty ( $input )) {
			$input = &$_REQUEST;
		}
		$query = array (
				'isFinish' => 1 
		);
		foreach ( $input as $k => $v ) {
			$v = trim ( $v );
			if ($v === '') {
				continue;
			}
			
			switch ($k) {
				case 'schoolID' :
					$v = ( int ) $v;
					if ($v > 0) {
						$query ['schoolID'] = $v;
					}
					break;
				case 'orderID' :
					$query ['_id'] = ( int ) $v;
					break;
				case 'uid' :
					$query ['userID'] = ( int ) $v;
					break;
				case 'devID' :
					$query ['devID'] = ( int ) $v;
					break;
				case 'devName' :
					$query ['devName'] = $v;
					break;
				case 'nickname' :
					$query ['nickname'] = $v;
					break;
				case 'rc_st' :
					$query ['createTime'] ['$gte'] = strtotime ( $v );
					break;
				case 'rc_et' :
					$query ['createTime'] ['$lte'] = strtotime ( $v );
					break;
			}
		}
		return $query;
	}
	private function getTableThItems() {
		return array (
				array (
						'text' => '订单ID',
						'order' => 'id' 
				),
				'单价',
				'取水秒数',
				'金额',
				'设备ID',
				'设备名',
				'学校',
				'状态',
				array (
						'text' => '订单时间',
						'order' => 'time' 
				),
				array (
						'text' => '用户ID',
						'order' => 'uid' 
				),
				'用户昵称' 
		);
	}
	private function getTableRows($list,$school_id=0) {
		$user=$_SESSION['admin'];
		$this->load->model ( 'Dev_mdl', 'dev' );
		$this->load->model ( 'User_mdl', 'users' );
		$orderTypes = array (
				BUY_MODE_HOT => '[热]',
				BUY_MODE_COLD => '[冷]',
				BUY_MODE_ONCE => '[洗衣机]',
				BUY_MODE_PULES_HOT => '[脉冲热]',
				BUY_MODE_PULES_COLD => '[脉冲冷]'
		);
		$devIdList = array_column ( $list, 'devID' );
		$userIdList = array_column ( $list, 'userID' );
		$devs = $this->dev->getListByFieldList ( 'id,name,schoolID', 'id', $devIdList );
		$users = $this->users->getListByFieldList ( 'id,nickname', 'id', $userIdList ); 
		$where_array=array();
		if($school_id>0){
			$where_array['id']=$school_id;
		}
		
		$this->load->model ( 'admin_mdl', 'adminmdl' );
		$is_admin=$this->adminmdl->isSuperManager($user['id']);
			
		if($is_admin){
			$schools = $this->school->getSchoolList();
		}else{
			$schools = $this->school->getSchoolList ($where_array);
		}
		
		$rows = array ();
		foreach ( $list as $v ) {
			
			$id = empty ( $v ['_id'] ) ? sprintf ( "%1d%08d", $v ['userID'] % 10, $v ['id'] ) : $v ['_id'];
			
			$uid = $v ['userID'];
			$type = isset ( $orderTypes [$v ['type']] ) ? $orderTypes [$v ['type']] : "[UNKNOW]";
			
			$devName = '';
			$schoolName = '';
			if (! empty ( $devs [$v ['devID']] )) {
				$dev = $devs [$v ['devID']];
				$devName = $dev ['name'];
				if (! empty ( $schools [$dev ['schoolID']] )) {
					$schoolName = $schools [$dev ['schoolID']] ['name'];
				}
			}
			$rows [] = array (
					$id,
					$type . $v ['price'] / 100,
					$v ['takeSec'],
					$v ['amount'] / 100,
					$v ['devID'],
					$devName,
					$schoolName,
					$v ['isFinish'] == 1 ? '结束' : '取水中',
					date ( 'Y-m-d H:i:s', $v ['updateTime'] ),
					$v ['userID'],
					empty ( $users [$v ['userID']] ) ? '' : $users [$v ['userID']] ['nickname'] 
			)
			;
		}
		return $rows;
	}
	public function move_old() {
		$this->load->database ();
		$task = new MoveOldOrders ( $this->db );
		$task->run ();
	}
}
class MoveOldOrders {
	protected $db;
	protected $timeLimit;
	protected $allTable;
	protected $fields;
	/**
	 *
	 * @param CI_DB_query_builder $db        	
	 */
	public function __construct($db) {
		$this->db = $db;
		$this->allTable = 'hs_order_old_all';
		$this->timeLimit = $this->getTimeLimit ();
		$this->fields = $this->getFields ();
	}
	private function getTimeLimit() {
		list ( $y, $m, $d ) = explode ( '-', date ( 'Y-m-d' ) );
		$y -= 1;
		return strtotime ( "{$y}-{$m}-{$d} 00:00:00" );
	}
	private function getFields() {
		$list = $this->db->list_fields ( $this->allTable );
		$list = array_filter ( $list, function ($field) {
			return ! ($field === 'id');
		} );
		return implode ( ',', $list );
	}
	public function run() {
		$tidSet = array (
				0,
				1,
				2,
				3,
				4,
				5,
				6,
				7,
				8,
				9 
		);
		
		foreach ( $tidSet as $tid ) {
			try {
				$this->db->trans_begin ();
				$this->db->trans_strict ( FALSE );
				$this->moveOne ( $tid );
				if ($this->db->trans_status () === FALSE) {
					throw new Exception ( '事务失败' );
				}
				$this->db->trans_commit ();
			} catch ( Exception $e ) {
				$this->db->trans_rollback ();
			}
		}
	}
	protected function moveOne($tid) {
		$trans = array ();
		$table = 'hs_order_' . $tid;
		// 表数据修正:
		$sql = "UPDATE `{$table}` SET createTime = updateTime - takeSec WHERE createTime<1400000000";
		$this->db->query ( $sql );
		// 转移的条件
		$where = "createTime < {$this->timeLimit}";
		// 转移到总表
		$idPrefix = $tid * 1e8;
		$select = "({$idPrefix}+id) as id," . $this->fields;
		$trans [] = "INSERT INTO {$this->allTable}
			(SELECT $select FROM {$table}
			WHERE {$where}
		)";
		// 删除订单表中相关行
// 		$trans [] = "DELETE FROM {$table} WHERE {$where}";
		
		echo '<hr><br>';
		foreach ( $trans as $sql ) {
			$rest = $this->db->query ( $sql );
			echo ( int ) $rest, '---', $sql, '<BR>';
		}
	}
}

// class ArrayList{
// 	public $list;
// 	public function __construct($list){
// 		$this->list = $list;
// 	}
	
// 	public function map($callback){
// 		$list = array_map($callback, $this->list);
// 		return new self($list);
// 	}
// 	public function filter($callback){
// 		$list = array_filter( $this->list,$callback);
// 		return new self($list);
// 	}
// 	public function find($callback){
// 		foreach ($this->list as $item){
// 			if($callback($item)){
// 				return $item;
// 			}
// 		}
// 	}
// 	public function join($glue){
// 		return implode($glue, $this->list);
// 	}
// 	public function pop(){
// 		return array_pop($this->list);
// 	}
// 	public function push($item){
// 		return array_push($this->list,$item);
// 	}
// 	public function shift(){
// 		return array_shift($this->list);
// 	}
// 	public function unshift($item){
// 		return array_unshift($this->list,$item);
// 	}
// 	public function slice($offset,$length=null){
// 		$list = array_slice($this->list, $offset,$length);
// 		return new self($list);
// 	}
// 	public function concat(){
		
// 	}
	
// }



